package com.link.play.fit.ai.ui.main.saveFood.details

import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.link.play.fit.ai.bean.BaseByDesFixBean
import com.link.play.fit.ai.bean.BaseFoodInfoBean
import com.link.play.fit.ai.bean.BaseScanFoodBean
import com.link.play.fit.ai.bean.ByDesFixBean
import com.link.play.fit.ai.bean.CalendarStatusData
import com.link.play.fit.ai.bean.CollectFoodInfoData
import com.link.play.fit.ai.bean.ReqCollectFoodData
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_SAVE_FOOD_COLLECT_DATA
import com.link.play.fit.ai.utils.ApiResult
import com.link.play.fit.ai.utils.ApiService
import com.link.play.fit.ai.utils.HttpResponse.safeApiCall
import com.link.play.fit.ai.utils.RetrofitClient
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class FixFoodViewmModel : ViewModel() {
    private val apiService = RetrofitClient.createService(ApiService::class.java)
    var desFixLiveBean: MutableStateFlow<BaseByDesFixBean> = MutableStateFlow(BaseByDesFixBean())

     fun saveFoodCollectList(data: CollectFoodInfoData){
        CloudStore.addToList(
           DOC_SAVE_FOOD_COLLECT_DATA,
            date = DOC_SAVE_FOOD_COLLECT_DATA,
            key = data.timeMillisecond,
            data = data
        )

    }

    /**
     * 根据json修正
     */
    fun byDescribe(data: ReqCollectFoodData) {
        viewModelScope.launch {
            when (val result = safeApiCall {
                apiService.fixByIssue(data)
            }) {
                is ApiResult.Success -> {
                    desFixLiveBean.update {
                        it.copy(status = 200, fixByIssueBean = result.data)
                    }
                }
                is ApiResult.BusinessError -> {
                    desFixLiveBean.update {
                        it.copy(status = result.status, msg = result.message)
                    }
                }
                is ApiResult.HttpError -> {
                    desFixLiveBean.update {
                        it.copy(status = result.code, msg = result.message)
                    }
                }
                is ApiResult.NetworkError -> {
                    desFixLiveBean.update {
                        it.copy(status = 400, msg = "Network connection failed")
                    }
                }
            }
        }
    }

}